package com.wzu.servlet;

import com.wzu.pojo.User;
import com.wzu.service.UserService;
import com.wzu.service.UserServiceImpl;
import com.wzu.pojo.Reader;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl(); // 假设已通过Spring注入

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("role");
        String adminPassword = request.getParameter("adminPassword");

        // 输入校验
        if (isInvalidInput(username, password, role)) {
            out.print("请完整填写注册信息（用户名/密码/角色必填）");
            return;
        }

        if ("Admin".equals(role) && !validateAdminPassword(adminPassword)) {
            out.print("管理员密码错误");
            return;
        }

        String hashedPassword = encryptPassword(password);
        if (hashedPassword == null) {
            out.print("注册失败，请重试");
            return;
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(hashedPassword);
        user.setRole(role);
        boolean userRegistered = userService.register(user);
        if (!userRegistered) {
            out.print("用户名已存在");
            return;
        }

// 直接用 user.getUser_id()
        System.out.println("注册用户ID：" + user.getUser_id());

        if (isReaderRole(role)) {
            Reader reader = new Reader();
            reader.setUserId(user.getUser_id());
            reader.setName(username); // 可先用用户名当作姓名
            reader.setGender("Male"); // 默认值或从请求参数获取
            reader.setAge(0);
            reader.setBorrow_limit(5);
            reader.setBorrow_period(30);
            reader.setCan_renew(true);

            boolean readerSuccess = userService.registerReader(reader);
            if (!readerSuccess) {
                out.print("读者注册失败");
                return;
            }
        }
        out.print("success");

    }

    private boolean isInvalidInput(String username, String password, String role) {
        return username == null || username.isEmpty() ||
                password == null || password.isEmpty() ||
                role == null || role.isEmpty();
    }

    private boolean validateAdminPassword(String inputPassword) {
        // 从配置获取真实密码，避免硬编码
        return "123456".equals(inputPassword); // 实际应从配置读取
    }

    private String encryptPassword(String password) {
        try {
            // 建议使用BCrypt而非MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(password.getBytes());
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    private boolean isReaderRole(String role) {
        return "Staff".equals(role) || "Admin".equals(role);
    }
}
